import {Injectable} from '@angular/core';
import {Platform, ToastController, App, NavController} from 'ionic-angular';
import $ from "jquery";
import {AdpMenuController} from "../../components/common/adp-menu/adp-menu.controller";

@Injectable()
export class BackButtonService {

    backButtonPressed: boolean = false;//控制硬件返回按钮是否触发，默认false

    constructor(public platform: Platform,
                public appCtrl: App,
                public toastCtrl: ToastController,
                private menuCtrl: AdpMenuController) {
    }

    /**
     * 系统返回键注册方法，页面组件需要特殊处理后退按钮的，在页面上写上backButtonHandle函数
     */
    registerBackButtonAction(): void {

        //registerBackButtonAction是系统自带的方法
        this.platform.registerBackButtonAction(() => {
            //如果有弹出层，则点击弹出层背景以关闭弹出层
            const backdrop = $('ion-backdrop');
            /*侧边栏固定包含一个'ion-backdrop*/
            if (backdrop.length > 1) backdrop.trigger('click');
            //关闭侧边栏
            this.menuCtrl.hideMenu();
            //获取当前NavController
            let activeNav: NavController = this.appCtrl.getActiveNav();
            let backButtonHandle = activeNav.getActive().instance.backButtonHandle;
            if(window['adpActionSheet'] && window['adpActionSheet'].instance) {
                window['adpActionSheet'].instance.bdClick();
            }
            //如果有后退处理函数则处理后退处理函数
            if (backButtonHandle) return backButtonHandle();
            //如果可以返回上一页，则执行pop
            if (activeNav.canGoBack()) {
                activeNav.pop();
            } else {
                this.showExit();
            }
        });
    }

    /**
     * 退出应用方法
     */
    private showExit(): void {
        //如果为true，退出
        if (this.backButtonPressed) {
            this.platform.exitApp();
        } else {
            //第一次按，弹出Toast
            this.toastCtrl.create({
                message: '再按一次退出应用',
                duration: 2000,
                position: 'middle',
            }).present();
            //标记为true
            this.backButtonPressed = true;
            //两秒后标记为false，如果退出的话，就不会执行了
            setTimeout(() => this.backButtonPressed = false, 2000);
        }
    }
}
